<?php

class FormManager {

    protected $field_errors = array();
    protected $handlers = array();
    public $validation_error = false;

    public function __construct() {

        //if(isset($_SESSION['form']['field_errors']))$this->field_errors = $_SESSION['form']['field_errors'];
        // $_SESSION['form']['field_errors'] = array();
    }

    public function addErorrMessageForField($name, $message) {
        
        if (!isset($_POST['action']))
            return;

        
        $this->field_errors[$_POST['action']][$name] = $message;
        //$_SESSION['form']['field_errors'][$_POST['action']][$name] = $message;
    }

    public function getErrorsForFields($form_name) {
        if (!isset($_POST['action']))
            return;

//        if(!$this->isValidationFailed($_POST['action']))
//        {
//            unset($_SESSION['form']['field_errors'][$_POST['action']]);
//            return false;
//        }

        return (isset($this->field_errors[$form_name]) ? $this->field_errors[$form_name] : false);
    }

    public function isValidationFailed($form_name) {
        return (isset($this->validation_error[$form_name]) ? $this->validation_error[$form_name] : false);
    }

    public function addHandler($handler) {
        $this->handlers[] = $handler;
    }

    public function unsetHandlers() {
        unset($this->handlers);
    }

    public function invokePOSTHandlers($request_context) {

        $res = false;
        if (session_status() != PHP_SESSION_ACTIVE)
            session_start();
        if (isset($_POST) && !empty($_POST['action']) && !empty($_POST['token'])) {
            $validate_res = true;
            $temp = array();
            $data = $_POST;
            foreach ($this->handlers as $key => $value) {
                if (method_exists($value, 'validate_post_' . strtolower($_POST['action']))) {
                    $validate_res = $value->{'validate_post_' . strtolower($_POST['action'])}($data, $temp, $this);
                    $this->savePOSTData($_POST['action'], $data);
                    if ($validate_res == VALIDATION_FAILED) {
                        $this->validation_error[$_POST['action']] = true;
                        Event::fireEvent('message', array('message' => 'При проверке формы обнаружены ошибки'));
                    }
                }
                if ((isset($_SESSION['form'][$_POST['action']]['token']) && $_SESSION['form'][$_POST['action']]['token'] == $_POST['token'])) {
                    if (method_exists($value, 'submit_post_' . strtolower($_POST['action'])) && $validate_res) {
                        $res = $value->{'submit_post_' . $_POST['action']}($data, $temp, $this);
                    }
                }
                else
                    unset($_SESSION['form'][$_POST['action']]['token']);
            }
        }
        if ($res instanceof Action)
            return $res;
        else
            return false;
    }

    public static function build_form($form_body_html, $form_name, $buttons) {
        $form_params = array(
            'body' => $form_body_html,
            'action' => $form_name,
            'buttons' => $buttons
        );
        $form_html = View::form_ex($form_params);
        return $form_html;
    }

    public function loadPOSTData($name) {
        if (isset($this->post_data[$name]))
            return $this->post_data[$name];
        else
            return array();
    }

    public function loadDataFromSession($name) {
        if (session_status() == PHP_SESSION_NONE)
            session_start();
        if (isset($_SESSION['form'][$name]))
            return $_SESSION['form'][$name];
        else
            return array();
    }

    public function getSessionVariable($name) {
        if (session_status() == PHP_SESSION_NONE)
            session_start();
        return (isset($_SESSION['values'][$name]) ? $_SESSION['values'][$name] : false);
    }

    public function setSessionVariable($name, $value) {
        if (session_status() == PHP_SESSION_NONE)
            session_start();
        $_SESSION['values'][$name] = $value;
    }

    public function unsetSessionVariable($name) {
        if (session_status() == PHP_SESSION_NONE)
            session_start();
        unset($_SESSION['values'][$name]);
    }

    public function clearSessionData() {
        if (session_status() == PHP_SESSION_NONE)
            session_start();
        unset($_SESSION['form']);
        unset($_SESSION['values']);
    }

    public function clearSessionDataByName($name) {
        if (session_status() == PHP_SESSION_NONE)
            session_start();
        unset($_SESSION['form'][$name]);
    }

    public function saveDataInToSession($data, $name) {
        if (session_status() == PHP_SESSION_NONE)
            session_start();
        $_SESSION['form'][$name] = $data;
    }

    public function savePOSTData($name, $data) {
        if (session_status() == PHP_SESSION_NONE)
            session_start();
        $this->post_data[$name] = $data;
    }

//        public function activateGETHandlers() {
//        if (isset($_GET) && !empty($_GET['action'])) {
//          
//            $validate_res = true;
//            $temp = array();
//            if (method_exists($this, 'validate_get_' . strtolower($_GET['action']))) {
//                //echo"Валидатор найден<br/>";
//                $validate_res = $this->{'validate_get_' . strtolower($_GET['action'])}($_GET, $temp);
//                if(!$validate_res) $this->validation_error = true;
//            }
//            if (method_exists($this, 'submit_get_' . strtolower($_GET['action'])) && $validate_res) {
//                //echo"Сабмиттер найден<br/>";
//                $this->{'submit_get_' . $_GET['action']}($_GET, $temp);
//            }
//        }   
//    }
}

?>
